package com.zsj.queue;


import java.util.Iterator;

/**
 * 环形数组实现队列
 */
public class RingQueueArray<E>
        implements Queue<E>,
        Iterable<E> {

    private E[] arr;

    private int head;

    private int tail;

    private int size;

    @SuppressWarnings("all")
    public RingQueueArray(int capacity) {
        arr = (E[]) new Object[capacity + 1];
        size = arr.length;
    }

    /**
     * 是当前索引所在位置
     * 去模总长度
     * index%length
     */
    @Override
    public boolean offer(E value) {
        if (isFull()) return false;//队列已满 不允许添加
        arr[tail] = value;
        tail = (tail + 1) % size;
        return true;
    }

    @Override
    public E poll() {
        if (isEmpty()) throw new NullPointerException("queue is empty");
        E value = arr[head];
        //这里不是很懂 移除元素 TODO
        head = (head + 1) % size;
        return value;
    }

    @Override
    public E peek() {
        if (isEmpty()) throw new NullPointerException("queue is empty");
        return arr[head];
    }

    @Override
    public boolean isEmpty() {
        return head == tail;
    }

    @Override
    public boolean isFull() {
        return (tail + 1) % size == head;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            int p = head;

            @Override
            public boolean hasNext() {
                return p != tail;
            }

            @Override
            public E next() {
                E value = arr[p];
                p = (p + 1) % size;
                return value;
            }
        };
    }
}
